//
//  MVVMTableViewController.m
//  DebugDemo
//
//  Created by XFB on 2019/5/7.
//  Copyright © 2019 ZhouCheng. All rights reserved.
//

#import "MVVMTableViewController.h"
#import "MJRefresh.h"

#import "TableModel.h"
#import "TableViewModel.h"

#import "ZCTableViewDataSource.h"
#import "ZCTableViewDelegate.h"

@interface MVVMTableViewController ()
{
    MJRefreshNormalHeader *refreshHeader;
    MJRefreshAutoNormalFooter *refreshFooter;
    UITableView *tableView;
    NSMutableArray *dataSource;
    TableViewModel *tableViewModel;
    ZCTableViewDataSource *tableViewDataSource;
    ZCTableViewDelegate *tableViewDelegate;
}

@end

@implementation MVVMTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupBasicSet];
    [self setupUI];
}

- (void)setupBasicSet
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"MVVM Demo";
}

- (void)setupUI
{
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NavBarHeight, ScreenW, ScreenH-NavBarHeight-BottomHeight) style:UITableViewStylePlain];
    [self.view addSubview:tableView];
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    tableViewDataSource = [[ZCTableViewDataSource alloc] init];
    tableViewDelegate = [[ZCTableViewDelegate alloc] init];
    tableView.dataSource = tableViewDataSource;
    tableView.delegate = tableViewDelegate;

    tableViewModel = [[TableViewModel alloc] init];
    dataSource = @[].mutableCopy;
    
    __weak typeof(self) weakSelf = self;
    refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefreshAction];
    }];
    tableView.mj_header = refreshHeader;
    [refreshHeader beginRefreshing];
    
    refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefreshAction];
    }];
    tableView.mj_footer = refreshFooter;
}

- (void)headerRefreshAction
{
    [tableViewModel headerRefreshRequestWithCallBack:^(NSArray *array) {
        self->dataSource = (NSMutableArray *)array;
        self->tableViewDataSource.array = self->dataSource;
        self->tableViewDelegate.array = self->dataSource;
        [self->refreshHeader endRefreshing];
        [self->tableView reloadData];
    }];
}

- (void)footerRefreshAction
{
    [tableViewModel footerRefreshRequestWithCallBack:^(NSArray *array) {
        [self->dataSource addObjectsFromArray:array];
        self->tableViewDataSource.array = self->dataSource;
        self->tableViewDelegate.array = self->dataSource;
        [self->refreshFooter endRefreshing];
        [self->tableView reloadData];
    }];
}


@end
